import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:get/get.dart';
import 'dart:convert';

class WebViewWidget extends StatefulWidget {
  final String url;
  final String? title;
  final bool showAppBar;
  final bool showNavigationButtons;
  final Function(String)? onWebMessage;
  final Function(String)? onUrlChanged;
  final Function(bool)? onLoadingChanged;
  final Map<String, String>? headers;
  final String? initialJavaScript;

  const WebViewWidget({
    super.key,
    required this.url,
    this.title,
    this.showAppBar = true,
    this.showNavigationButtons = true,
    this.onWebMessage,
    this.onUrlChanged,
    this.onLoadingChanged,
    this.headers,
    this.initialJavaScript,
  });

  @override
  State<WebViewWidget> createState() => _WebViewWidgetState();
}

class _WebViewWidgetState extends State<WebViewWidget> {
  InAppWebViewController? _webViewController;
  bool _isLoading = true;
  bool _canGoBack = false;
  bool _canGoForward = false;
  String _currentUrl = '';
  String _pageTitle = '';

  @override
  void initState() {
    super.initState();
    _currentUrl = widget.url;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.showAppBar ? _buildAppBar() : null,
      body: _buildWebView(),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Text(
        widget.title ?? (_pageTitle.isNotEmpty ? _pageTitle : '网页浏览'),
        style: const TextStyle(fontSize: 16),
      ),
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: Colors.black),
        onPressed: () => Navigator.of(context).pop(),
      ),
      actions: widget.showNavigationButtons ? _buildNavigationActions() : null,
    );
  }

  List<Widget> _buildNavigationActions() {
    return [
      // 后退按钮
      IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          color: _canGoBack ? Colors.black : Colors.grey,
        ),
        onPressed: _canGoBack ? _goBack : null,
      ),
      // 前进按钮
      IconButton(
        icon: Icon(
          Icons.arrow_forward_ios,
          color: _canGoForward ? Colors.black : Colors.grey,
        ),
        onPressed: _canGoForward ? _goForward : null,
      ),
      // 刷新按钮
      IconButton(
        icon: const Icon(Icons.refresh, color: Colors.black),
        onPressed: _reload,
      ),
    ];
  }

  Widget _buildWebView() {
    return Stack(
      children: [
        // WebView
        InAppWebView(
          initialUrlRequest: URLRequest(
            url: WebUri(widget.url),
            headers: widget.headers,
          ),
          initialSettings: InAppWebViewSettings(
            // 隐藏滚动条
            verticalScrollBarEnabled: false,
            horizontalScrollBarEnabled: false,
            // 启用JavaScript
            javaScriptEnabled: true,
            // 允许混合内容
            mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
            // 允许文件访问
            allowFileAccessFromFileURLs: true,
            allowUniversalAccessFromFileURLs: true,
            // 启用DOM存储
            domStorageEnabled: true,
            // 启用数据库
            databaseEnabled: true,
            // 设置用户代理
            userAgent: 'GluzApp/1.0',
            // 启用缩放
            supportZoom: true,
            // 设置默认字体大小
            defaultFontSize: 16,
            // 启用硬件加速
            useWideViewPort: true,
            loadWithOverviewMode: true,
            // 允许不安全的内容
            allowsInlineMediaPlayback: true,
            // 允许混合内容
            allowsBackForwardNavigationGestures: true,
          ),
          onWebViewCreated: (InAppWebViewController controller) {
            _webViewController = controller;

            // 添加NativeBridge处理器 - 兼容原生Android/iOS的交互方式
            controller.addJavaScriptHandler(
              handlerName: 'NativeBridge',
              callback: (args) {
                print('NativeBridge 处理器被调用，参数: $args');
                if (args.isNotEmpty) {
                  final message = args[0].toString();
                  print('NativeBridge 消息: $message');
                  _handleNativeBridgeMessage(message);
                } else {
                  print('NativeBridge 参数为空');
                }
              },
            );
          },
          onLoadStart: (controller, url) {
            _setLoading(true);
            _updatePageInfo(url?.toString(), null);
          },
          onLoadStop: (controller, url) async {
            _setLoading(false);
            _updatePageInfo(url?.toString(), null);
            _updateNavigationState();
            
            // 注入自定义JavaScript
            await _injectCustomJavaScript();
            
            // 获取页面标题
            final title = await controller.getTitle();
            _updatePageInfo(null, title);
            print('页面加载完成，JavaScript已注入');
          },
          onReceivedError: (controller, request, errorResponse) {
            _setLoading(false);
            print('WebView加载错误: ${errorResponse?.description}');
          },
          onProgressChanged: (controller, progress) {
            print('加载进度: $progress%');
          },
          onConsoleMessage: (controller, consoleMessage) {
            print('WebView控制台: ${consoleMessage.message}');
          },
        ),
        
        // 加载指示器
        _isLoading
            ? Container(
                color: Colors.white,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      LoadingAnimationWidget.staggeredDotsWave(
                        color: Colors.blue,
                        size: 50,
                      ),
                      const SizedBox(height: 20),
                      const Text(
                        '正在加载...',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            : const SizedBox.shrink(),
      ],
    );
  }

  void _setLoading(bool loading) {
    setState(() {
      _isLoading = loading;
    });
    widget.onLoadingChanged?.call(loading);
  }

  void _updatePageInfo(String? url, String? title) {
    setState(() {
      if (url != null) _currentUrl = url;
      if (title != null) _pageTitle = title;
    });
    if (url != null) {
      widget.onUrlChanged?.call(url);
    }
  }

  void _updateNavigationState() {
    _webViewController?.canGoBack().then((value) {
      setState(() {
        _canGoBack = value;
      });
    });
    _webViewController?.canGoForward().then((value) {
      setState(() {
        _canGoForward = value;
      });
    });
  }

  void _goBack() {
    if (_canGoBack) {
      _webViewController?.goBack();
    }
  }

  void _goForward() {
    if (_canGoForward) {
      _webViewController?.goForward();
    }
  }

  void _reload() {
    _webViewController?.reload();
  }


  void _handleNativeBridgeMessage(String message) {
    print('处理NativeBridge消息: $message');
    
    try {
      // 解析JSON消息
      final Map<String, dynamic> data = json.decode(message);
      final String action = data['action'] ?? '';
      final String webview = data['webview'] ?? '';
      final dynamic dataParam = data['data'];
      final Map<String, dynamic>? otherParams = data['otherParams'] != null 
          ? Map<String, dynamic>.from(data['otherParams']) 
          : null;
      
      print('解析消息 - action: $action, webview: $webview');
      
      switch (action) {
        case 'navigateBack':
          print('执行返回操作');
          Get.back();
          break;
          
        case 'navigateTo':
          print('执行导航到新页面');
          _handleNavigateTo(dataParam, webview);
          break;
          
        case 'redirectTo':
          print('执行重定向');
          _handleRedirectTo(dataParam, webview);
          break;
          
        case 'login':
          print('执行登录操作');
          _handleLogin();
          break;
          
        case 'activeLogin':
          print('执行主动登录');
          _handleActiveLogin();
          break;
          
        case 'setLockOrientation':
          print('设置屏幕方向');
          _handleSetLockOrientation(otherParams);
          break;
          
        case 'goHome':
          print('返回首页');
          _handleGoHome(data);
          break;
          
        case 'call':
          print('执行通话操作');
          _handleCall(dataParam);
          break;
          
        case 'initiateChat':
          print('发起聊天');
          _handleInitiateChat(dataParam);
          break;
          
        case 'aliPay':
          print('支付宝支付');
          _handleAliPay(dataParam);
          break;
          
        case 'wxPay':
          print('微信支付');
          _handleWxPay(dataParam);
          break;
          
        case 'joinLive':
          print('加入直播');
          _handleJoinLive(dataParam);
          break;
          
        case 'downloadFile':
          print('下载文件');
          _handleDownloadFile(dataParam);
          break;
          
        case 'upDateUser':
          print('更新用户信息');
          _handleUpdateUser(dataParam);
          break;
          
        case 'makePhoneCall':
          print('拨打电话');
          _handleMakePhoneCall(dataParam);
          break;
          
        case 'sendGood':
          print('发送商品');
          _handleSendGood(dataParam);
          break;
          
        default:
          print('未知的操作类型: $action');
      }
    } catch (e) {
      print('解析NativeBridge消息失败: $e');
    }
  }

  Future<void> _injectCustomJavaScript() async {
    String script = '''
      // 创建全局消息处理器
      window.flutterMessageHandler = function(message) {
        console.log('收到Flutter消息:', message);
        // 这里可以处理来自Flutter的消息
      };
      
      // 向Flutter发送消息的函数
      window.sendMessageToFlutter = function(message) {
        if (window.flutter_inappwebview) {
          window.flutter_inappwebview.callHandler('onWebMessage', message);
        }
      };
      
      // 兼容原生Android/iOS的NativeBridge接口
      window.NativeBridge = {
        postMessage: function(json) {
          console.log('NativeBridge.postMessage 被调用:', json);
          console.log('flutter_inappwebview 对象:', window.flutter_inappwebview);
          if (window.flutter_inappwebview) {
            console.log('调用 flutter_inappwebview.callHandler');
            window.flutter_inappwebview.callHandler('NativeBridge', json);
          } else {
            console.log('flutter_inappwebview 对象不存在');
          }
        }
      };
      
      // 页面加载完成后的初始化
      document.addEventListener('DOMContentLoaded', function() {
        console.log('页面加载完成');
        console.log('NativeBridge 对象:', window.NativeBridge);
        // 可以在这里添加页面特定的初始化代码
      });
      
      // 立即检查NativeBridge是否可用
      console.log('NativeBridge 注入完成:', window.NativeBridge);
    ''';

    // 添加自定义JavaScript
    if (widget.initialJavaScript != null) {
      script += '\n' + widget.initialJavaScript!;
    }

    print('注入JavaScript脚本...');
    try {
      await _webViewController?.evaluateJavascript(source: script);
      print('JavaScript注入成功');
    } catch (e) {
      print('JavaScript注入失败: $e');
    }
  }

  // 公共方法：向Web页面发送消息
  Future<void> sendMessageToWeb(String message) async {
    final script = '''
      if (window.flutterMessageHandler) {
        window.flutterMessageHandler('$message');
      }
    ''';
    await _webViewController?.evaluateJavascript(source: script);
  }

  // 公共方法：执行JavaScript代码
  Future<dynamic> evaluateJavaScript(String script) async {
    return await _webViewController?.evaluateJavascript(source: script);
  }

  // 公共方法：获取当前URL
  String get currentUrl => _currentUrl;

  // 公共方法：获取页面标题
  String get pageTitle => _pageTitle;

  // 处理导航到新页面
  void _handleNavigateTo(dynamic dataParam, String webview) {
    print('导航到新页面: $dataParam, webview: $webview');
    
    // 根据webview类型构建基础URL
    String baseUrl = '';
    switch (webview) {
      case 'zWebView':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 货代URL
        break;
      case 'zWebViewOline':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 线上展会URL
        break;
      case 'zWebViewShop':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 商城URL
        break;
      case 'zWebViewDaixiao':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 代销URL
        break;
      default:
        print('未知的webview类型: $webview');
        return;
    }
    
    // 构建完整URL
    String fullUrl = baseUrl + dataParam.toString();
    
    // 导航到新的WebView页面
    Get.to(() => WebViewWidget(
      url: fullUrl,
      title: '新页面',
    ));
  }

  // 处理重定向
  void _handleRedirectTo(dynamic dataParam, String webview) {
    print('重定向到: $dataParam, webview: $webview');
    
    // 根据webview类型构建基础URL
    String baseUrl = '';
    switch (webview) {
      case 'zWebView':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 货代URL
        break;
      case 'zWebViewOline':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 线上展会URL
        break;
      case 'zWebViewShop':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 商城URL
        break;
      case 'zWebViewDaixiao':
        baseUrl = 'https://shop1.gluz.com.cn/ts/'; // 代销URL
        break;
      default:
        print('未知的webview类型: $webview');
        return;
    }
    
    // 构建完整URL
    String fullUrl = baseUrl + dataParam.toString();
    
    // 重定向：替换当前页面
    Get.off(() => WebViewWidget(
      url: fullUrl,
      title: '新页面',
    ));
  }

  // 处理登录
  void _handleLogin() {
    print('执行登录操作');
    // TODO: 实现登录逻辑
    // 可以调用Get.to()导航到登录页面
  }

  // 处理主动登录
  void _handleActiveLogin() {
    print('执行主动登录');
    // TODO: 实现主动登录逻辑
  }

  // 处理设置屏幕方向
  void _handleSetLockOrientation(Map<String, dynamic>? otherParams) {
    print('设置屏幕方向: $otherParams');
    // TODO: 实现屏幕方向设置
  }

  // 处理返回首页
  void _handleGoHome(Map<String, dynamic> data) {
    print('返回首页: $data');
    // TODO: 实现返回首页逻辑
  }

  // 处理通话
  void _handleCall(dynamic dataParam) {
    print('执行通话操作: $dataParam');
    // TODO: 实现通话逻辑
  }

  // 处理发起聊天
  void _handleInitiateChat(dynamic dataParam) {
    print('发起聊天: $dataParam');
    // TODO: 实现聊天逻辑
  }

  // 处理支付宝支付
  void _handleAliPay(dynamic dataParam) {
    print('支付宝支付: $dataParam');
    // TODO: 实现支付宝支付逻辑
  }

  // 处理微信支付
  void _handleWxPay(dynamic dataParam) {
    print('微信支付: $dataParam');
    // TODO: 实现微信支付逻辑
  }

  // 处理加入直播
  void _handleJoinLive(dynamic dataParam) {
    print('加入直播: $dataParam');
    // TODO: 实现直播逻辑
  }

  // 处理下载文件
  void _handleDownloadFile(dynamic dataParam) {
    print('下载文件: $dataParam');
    // TODO: 实现文件下载逻辑
  }

  // 处理更新用户信息
  void _handleUpdateUser(dynamic dataParam) {
    print('更新用户信息: $dataParam');
    // TODO: 实现用户信息更新逻辑
  }

  // 处理拨打电话
  void _handleMakePhoneCall(dynamic dataParam) {
    print('拨打电话: $dataParam');
    // TODO: 实现拨打电话逻辑
  }

  // 处理发送商品
  void _handleSendGood(dynamic dataParam) {
    print('发送商品: $dataParam');
    // TODO: 实现发送商品逻辑
  }
} 